import { t } from 'i18next'
import React, { FC, useEffect, useState } from 'react'

import { FixedSizeList as List, ListChildComponentProps } from 'react-window'
import AutoSizer from 'react-virtualized-auto-sizer'
import { Droppable, Draggable, DragDropContextProvider } from '@/plugins/dnd'
import { TableItem } from './TableItem'
import { THeader } from './THeader'
import { Wrap } from './style'
import { ListItemGhost, TableEmpty } from '../../../../components'
import { ActionButtons } from '../../actionButtons'
import { Mt, revert_mt } from '@/api/manager/mt'
import { DcsModel } from '@/api/manager/dcs/interface'
import { Meeting } from '@/api/manager/meeting'
import useLock from '@/hooks/useLock'
import { fetchCancelChairman, fetchCancelSpeaker } from '@/api/manager/actions'
import { Confirm } from '@/components/Alert'
import { store as SmsStore } from '@/pages/manager/blocks/sms/store'
import { useMccStore } from '@/pages/manager/store'
import { useTableDcsStore } from './store'
import { useMonitorStore } from '../../../monitor/store'

interface RowRendererProps extends ListChildComponentProps {
	data: DcsModel[]
}
const rowRenderer = React.memo(({ data: list, index, style }: RowRendererProps) => {
	const rowData = list[index]
	const dataTransfer = () => {
		let mt = revert_mt(rowData.mcc)
		mt.dcs_oper = rowData.dcs.isDcs ? 1 : 0
		return {
			data: {
				mt,
				tableDcs: {},
			},
			from: 'tableDcs',
			// ...rxMainOut.getValue.nativeMonitor(rowData.mcc),
			...useMonitorStore.getState().nativeMonitorDropParse(rowData.mcc),
		}
	}
	const isOdd = index % 2 ? true : false
	return (
		<Draggable
			style={style}
			index={index}
			dataTransfer={dataTransfer}
			ghostRender={<ListItemGhost data={rowData.mcc} />}
		>
			<TableItem rowData={rowData} isOdd={isOdd} />
		</Draggable>
	)
})
export const TableDcs: FC<{ isOrganize: boolean }> = ({ isOrganize }) => {
	const [list, setList] = useState<DcsModel[]>([])
	const _list = useTableDcsStore((state) => state.list)
	useEffect(() => {
		const l = _list.filter((x) => x.status.isMatchSearch)
		setList(l)
	}, [_list])
	const handleDrop = useLock(async (dataTransfer: any, index: null, ev: DragEvent) => {
		if (
			dataTransfer &&
			dataTransfer.data &&
			dataTransfer.data.mt &&
			!(ev.target as HTMLElement).classList.contains('only-for-drop')
		) {
			const meetingMoid = useMccStore.getState().mccInfo.meetingMoid
			let mt = dataTransfer.data.mt
			if (dataTransfer.from === 'speaker') {
				await fetchCancelSpeaker(meetingMoid, mt.isMt ? new Mt(mt) : new Meeting(mt)).then((res) => {
					if (res && res.success) {
						if (mt.isMt) SmsStore.getState().updateList([mt])
					}
				})
			}
			if (dataTransfer.from === 'chairman') {
				const isMeetingAdminOrCreator = useMccStore.getState().isMeetingAdminOrCreator
				if (isMeetingAdminOrCreator) {
					await fetchCancelChairman(meetingMoid, new Mt(mt)).then((res) => {
						if (res && res.success) {
							SmsStore.getState().updateList([mt])
						}
					})
				} else {
					Confirm(t('若取消自己管理方，您将失去管理方权限'), () =>
						fetchCancelChairman(meetingMoid, new Mt(mt))
					)
				}
			}
		}
	})
	return (
		<Wrap isOrganize={isOrganize}>
			{list.length > 0 ? (
				<>
					<THeader></THeader>
					<div className="table-body">
						<AutoSizer>
							{({ width, height }) => (
								<DragDropContextProvider>
									<Droppable isPlaceholder={false} onDrop={handleDrop}>
										{(setDroppableRef) => (
											<List
												width={width}
												height={height}
												itemCount={list.length}
												itemSize={30}
												itemData={list}
												outerRef={setDroppableRef}
												itemKey={(index, data) => data[index].mtKey}
												className="only-for-drop"
											>
												{rowRenderer}
											</List>
										)}
									</Droppable>
								</DragDropContextProvider>
							)}
						</AutoSizer>
					</div>
					<ActionButtons />
				</>
			) : (
				<TableEmpty />
			)}
		</Wrap>
	)
}
